package com.aruba.attendance.extension.photo

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.core.content.FileProvider
import com.apkfuns.logutils.LogUtils
import com.aruba.attendance.BuildConfig
import java.io.File

/**
 * 拍照扩展函数
 * Created by aruba on 2023/2/15.
 */
fun ComponentActivity.photo(
    activityResult: ActivityResultLauncher<Intent>,
    dirPath: String
): String =
    run {
        val getImageByCamera = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val outFilePath = "${dirPath}/Photo/"
        val dir = File(outFilePath)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val capturePath = outFilePath + System.currentTimeMillis() + ".jpg"
        LogUtils.i(capturePath)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val imgUri: Uri = FileProvider.getUriForFile(
                this,
                "${BuildConfig.APPLICATION_ID}.fileprovider",
                File(capturePath)
            )
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, imgUri)
        } else {
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(File(capturePath)))
        }
        getImageByCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1)

        activityResult.launch(getImageByCamera)
        return capturePath
    }
